# -*- coding:utf-8 -*-

import SocketServer
import simplejson as json
from mycoolpai.initclass import CPConf
from datalayer.datasource import CPData

class TCPRequestHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        '''
        处理客户端请求的方法
        '''
        msg = self.rfile.readline()
        self.rfile.close()
        msg = str(msg).strip()
        #result是回复给前台的结果
        result = dict()
        #用json格式交换数据
        msg = json.loads(msg)
        if (not isinstance(msg, dict)) or (msg.get('type',None) is None):
            result['type'] = 2
            result['info'] = 'format error'
            self.wfile.write(json.dumps(result)+'\r\n')
            return
        info_type = msg['type']
        if info_type == 'check_user_availability':
            #查询是否被注册
            field = msg['field']
            field_value = msg['value']
            mydata = CPData()
            if mydata.check_user_availability(field, field_value):
                #说明查到了这个字段的这个值
                result['type'] = 0
            else:
                result['type'] = 1
            self.wfile.write(json.dumps(result)+'\r\n')
        elif info_type == 'user_register':
            email_value = msg['email']
            passwd_value = msg['password']
            nickname_value = msg['nickname']
            mydata = CPData()
            status,status_info = mydata.user_register(email_value, passwd_value, nickname_value)
            if status is True:
                result['type'] = 1
                result['info'] = status_info
            else:
                result['type'] = 0
                result['info'] = status_info
            self.wfile.write(json.dumps(result)+'\r\n')
            
        


class MyTCPServer():
    def __init__(self):
        conf = CPConf()
        self.port = int(conf.getValue('tcp_port'))
    def run(self):
        server=SocketServer.ThreadingTCPServer(('192.168.1.88',self.port),TCPRequestHandler)
        print 'waiting for connection...'
        server.serve_forever()
